using TripleA.Core.Database;
using TripleA.Core.Database.SqlServer;
using TripleA.Core.Interfaces.Entities;
using TripleA.Core.Interfaces.Exceptions;

namespace TripleA.Core.Extensions.Database
{
    public class SqlServer2008AssertLoginStep<T> : SqlServerCommandStep<T>
        where T : Context
    {
        public string Username { get; set; }

        public override void PreValidate(T context)
        {
            if (string.IsNullOrWhiteSpace(Username))
                throw new StepConfigurationException("Username property not set, null or empty");
        }

        protected virtual ISqlStatement BuildStatement()
        {
            return SqlServerStatement.Create("SELECT COUNT(*) FROM master.sys.server_principals WHERE name=")
                .InsertParameter("@pUserName", Username);
        }

        public override void Execute(T context)
        {
            ExpectedRows = 1;
            Statement = BuildStatement();            
            ExecuteGetInt(context);
        }

        protected override string ExpectedExceptionMessage(int expected, int actual)
        {
            return string.Format("'{0}' does not have a server login!", Username);
        }
    }
}